<template>
  <div>
    <div class="bind-page" v-if="!loading">
      <van-swipe v-if="detail.images && detail.images.length > 0" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(item, index) in detail.images" :key="index" >
          <div class="swiper-item">
            <van-image class="info-img" lazy-load :src="item.fileUrl"/>
          </div>
        </van-swipe-item>
      </van-swipe>
      <div class="page-section">
        <div class="section-header">绑定设备</div>
        <div class="section-box">
          <div class="item-row">
            <span>设备编号（ID）</span>
            <span class="low-show">{{detail.devNo}}</span>
          </div>
          <div class="item-row">
            <span>设备名称</span>
            <span class="low-show">{{detail.name}}</span>
          </div>
        </div>
      </div>

      <div class="page-section">
        <div class="section-header">位置绑定</div>
        <div class="section-box">
          <div class="area-flex">
              <div class="picker-right" @click="showVenuesPicker = true">
                <span class="asset-name" v-if="venues.text">{{venues.text}}</span>
                <span v-else>请选择建筑</span>
                <van-icon name="arrow" class="picker-row-arrow" />
              </div>

              <div class="picker-right" @click="showFloorPicker = true">
                <span class="asset-name" v-if="floor.text">{{floor.text}}</span>
                <span v-else>请选择楼层</span>
                <van-icon name="arrow" class="picker-row-arrow" />
              </div>

              <div class="picker-right" @click="showAreaPicker = true">
                <span class="asset-name" v-if="area.text">{{area.text}}</span>
                <span v-else>请选择区域</span>
                <van-icon name="arrow" class="picker-row-arrow" />
              </div>

          </div>

          <div class="planeFigure_box_container" v-if="location.floorPlaneFigure">
            <div class="planeFigure_box">
              <point
                featureType="All"
                :areaPoints="location.metaAreaPoint"
                :points="location.points"
                :pointImg="location.floorPlaneFigure"
                v-if="location.floorPlaneFigure && location.metaAreaPoint !==false"
                @input="changePoingts"
              ></point>
            </div>

          </div>
        </div>
      </div>

      <div class="section-box mt20">
        <div class="item-row">
          <span>资产绑定（选填）</span>
          <div class="picker-right" @click="bindAsset">
            <span class="asset-name" v-if="asset && asset.id">{{asset.name}}</span>
            <span v-else>请选择资产</span>
            <van-icon name="arrow" class="picker-row-arrow" />
          </div>
        </div>
      </div>
      <div class="footer" @click="onBind">确定绑定</div>

      <van-popup v-model="showVenuesPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="venuesOptions"
          @cancel="showVenuesPicker = false"
          @confirm="onVenuesConfirm"
        />
      </van-popup>
      <van-popup v-model="showFloorPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="floorOptions"
          @cancel="showFloorPicker = false"
          @confirm="onFloorConfirm"
        />
      </van-popup>
      <van-popup v-model="showAreaPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="areaOptions"
          @cancel="showAreaPicker = false"
          @confirm="onAreaConfirm"
        />
      </van-popup>
    </div>
    <div v-else class="loading">
      <van-loading color="#1989fa" size="42"/>
    </div>
  </div>
</template>
<script>
import { getDeviceDetail, bindDevice, updateDevice } from '@/api/device'
import { floorList, venuesList, areaList } from '@/api/common'
import Point from '@/components/point'

export default {
  data () {
    return {
      location: {
        points: [],
        metaAreaPoint: [],
        floorPlaneFigure: ''
      },
      venues: {},
      area: {},
      floor: {},
      showVenuesPicker: false,
      showAreaPicker: false,
      showFloorPicker: false,
      venuesOptions: [],
      floorOptions: [],
      areaOptions: [],
      loading: false,
      origin: null,
      timer: null,
      id: null,
      qrCode: null,
      asset: null,
      interval: 3000,
      circular: true,
      detail: {},
      isSubmit: false
    }
  },
  components: {
    Point
  },
  created () {
    const query = this.$route.query
    this.id = query.id
    this.qrCode = query.qrCode
    this.origin = query.origin
    this.getVenueslist()
    this.getDeviceInfo()

    const _this = this
    dd.onMessage = function (data) {
      _this.asset = data
    }
  },
  methods: {
    changePoingts (val) {
      console.log(val)
      // this.$dialog.alert({message: JSON.stringify(val)})
      // this.location.points = val
      this.$set(this.location, 'points', val)
    },
    onVenuesConfirm (value) {
      this.showVenuesPicker = false

      if (value.value === this.venues.value) {
        return
      }
      this.venues = value
      this.floor = {}
      this.area = {}
      this.areaOptions = []
      this.location.points = []
      this.location.floorPlaneFigure = false
      // 选择场馆获取楼层数据并切换以后清除楼层数据
      this.getFloorlist(value.value)
    },
    onFloorConfirm (value) {
      this.showFloorPicker = false
      if (value.value === this.floor.value) {
        return
      }
      this.floor = value

      this.area = {}
      // 此处由于图片打点组件不会重新渲染数据，采用重绘机制来更新页面
      this.location.floorPlaneFigure = ''
      this.location.points = []
      this.getAreaList(value.value)
      setTimeout(() => {
        // 延迟500ms重新获取楼层对应的图片及点位数据完成页面重新绘制
        this.floorOptions &&
          this.floorOptions.map((item) => {
            // 判断楼层列表id,与当前选中的id相等
            if (item.value === value.value) {
              if (!item.planeFigure) {
                this.$toast.fail('没有上传楼层区域图,无法进行绘制')
              }
              this.location.floorPlaneFigure = item.planeFigure
            }
          })
      }, 500)
    },
    onAreaConfirm (value) {
      this.showAreaPicker = false
      if (value.value === this.area.value) {
        return
      }
      this.area = value
      // 组件刷新
      this.location.metaAreaPoint = false
      setTimeout(() => {
        this.areaOptions.map((item) => {
          if (item.value === value.value) {
            if (item.figurePoints) {
              this.$set(this.location, 'metaAreaPoint', JSON.parse(item.figurePoints))
            } else {
              this.$set(this.location, 'metaAreaPoint', [])
            }
          }
        })
      }, 500)
    },
    onBind () {
      if (this.isSubmit) {
        return
      }
      if (!this.area.value) {
        this.$toast({
          type: 'error',
          message: '请选择区域'
        })
        return
      }
      this.isSubmit = true

      const assetId = this.asset?.id
      // 设备绑定，区域位置更新
      bindDevice({
        assetId: assetId,
        deviceId: this.id,
        qrCode: this.qrCode
      }).then(() => {
        // 先绑定二维码，以确定资产和设备的关联关系
        updateDevice({
          id: this.id,
          location: this.area.value,
          floorId: this.floor.value,
          venuesId: this.venues.value,
          point: JSON.stringify(this.location.points)
        }).then(() => {
          this.$toast({
            type: 'success',
            message: '绑定成功',
            onOpened () {
              this.timer = setTimeout(() => {
                dd.navigateBack({
                  delta: 3
                })
              }, 2000)
            }
          })
        }).catch(() => {
          this.isSubmit = false
        })
      }).catch(() => {
        this.isSubmit = false
      })
      // Promise.all([bindDevice({
      //   assetId: this.asset.id,
      //   deviceId: this.id,
      //   qrCode: this.qrCode
      // }), updateDevice({
      //   id: this.id,
      //   location: this.area.value,
      //   point: JSON.stringify(this.location.points)
      // })]).then(() => {
      //   // if (this.origin && this.origin === 'tabbar') {
      //   //   content = '绑定成功,2s跳转到详情页'
      //   // }
      //   this.$toast({
      //     type: 'success',
      //     message: '绑定成功',
      //     onOpened () {
      //       this.timer = setTimeout(() => {
      //       // if (this.origin && this.origin === 'tabbar') {
      //       //   dd.redirectTo({
      //       //     url: `/pages/device/deviceDetail/deviceDetail?id=${this.id}`
      //       //   })
      //       // } else {
      //         dd.navigateBack({
      //           delta: 3
      //         })
      //       // }
      //       }, 2000)
      //     }
      //   })
      // }).catch(() => {
      //   this.isSubmit = false
      // })
    },
    bindAsset () {
      dd.navigateTo({ url: '/pages/asset/bindAsset/index?from=choose' })
    },
    getDeviceInfo () {
      this.loading = true
      getDeviceDetail(this.id).then(res => {
        const data = res.data
        this.detail = data
        data.points = data.point || '[]'
        data.metaAreaVo = data.metaAreaVo || {}
        this.location.floorPlaneFigure = data.metaAreaVo.floorPlaneFigure ? data.metaAreaVo.floorPlaneFigure : ''
        // 获取相应楼层区域下拉,展示
        if (data.metaAreaVo.venuesId) {
          this.venues = {
            text: data.metaAreaVo.venuesName,
            value: data.metaAreaVo.venuesId
          }
          this.getFloorlist(data.metaAreaVo.venuesId)
        }
        if (data.metaAreaVo.floorId) {
          this.floor = {
            text: data.metaAreaVo.floorName,
            value: data.metaAreaVo.floorId
          }
          this.getAreaList(data.metaAreaVo.floorId)
        }
        if (data.metaAreaVo.id) {
          this.area = {
            text: data.metaAreaVo.areaName,
            value: data.metaAreaVo.id
          }
          this.getAreaList(data.metaAreaVo.floorId)
        }
        // 点位信息
        try {
          this.location.points = JSON.parse(data.points)
          this.location.metaAreaPoint = JSON.parse(data.metaAreaVo.figurePoints)
        } catch (err) {
          console.log(err)
          this.location.metaAreaPoint = []
          this.location.points = []
        }

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getVenueslist () {
      venuesList().then((res) => {
        this.venuesOptions = res.rows.map(item => ({
          text: item.venuesName,
          value: item.id
        }))
      })
    },
    // 获取楼层数据
    getFloorlist (venuesId) {
      floorList({ venuesId }).then((res) => {
        this.floorOptions = res.rows.map(item => ({
          text: item.floorName,
          value: item.id,
          planeFigure: item.planeFigure
        }))
      })
    },
    getAreaList (id) {
      areaList({ floorId: id }).then((res) => {
        this.areaOptions = res.rows.map(item => ({
          text: item.areaName,
          value: item.id,
          figurePoints: item.figurePoints
        }))
      })
    }
  },
  destroyed () {
    const timer = this.timer
    timer && clearTimeout(timer)
  }
}
</script>
<style scoped>
.loading {
  margin-top: 200px;
  text-align: center;
}
.bind-page {
  padding-bottom: 100px;
}
.section-header {
  color: #999;
  font-size: 14px;
  padding:  10px 12px;
}
.section-box {
  background-color: #fff;
  padding: 0 12px;
}
.item-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #ececec;
}
.row-title {
  font-size: 14px;
  color: #333;
}
.item-row:last-child {
  border-bottom: none;
}
.low-show {
  color: #666;
}
.hight-show {
  color: #FF0000;
}
.mt20 {
  margin-top: 10px;
}
.swiper-item{
  display: block;
  height: 197px;
  background-color: #fff;
}
.info-img {
  width: 100%;
  height: 100%;
}
.picker-right {
  color: #999;
  font-size: 14px;
  flex: 1;
  text-align: right;
}
.asset-name {
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.picker-row-arrow {
  margin-left: 8px;
}
.area-flex {
  display: flex;
}
.area-flex .picker-right {
  text-align: center;
  height: 50px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.area-flex .asset-name {
  display: inline-block;
  max-width: 100px;
  word-break: break-all;

}
.planeFigure_box_container {
  /* padding: 10px 0; */
  text-align: center;
}
.planeFigure_box {
  display: inline-block;
  width: 300px;
  height: 300px;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 100;
  width: 100%;
  height: 80px;
  line-height: 80px;
  text-align: center;
  background-color: #0079FE;
  color: #fff;
}
</style>
